import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Main {
    /*
    二叉树后序遍历(非递归)
     */
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = new TreeNode();
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {//遍历左子树
                stack.push(cur);
                cur = cur.left;
            }
            //右子树
            TreeNode top = stack.peek();//记录栈顶元素,防止栈顶的左右还有节点(后序是先左右子树再是根)
            if(top.right == null || top.right == prev) {//当右子树为空时,那么就弹出,并存入当前节点()
                stack.pop();
                list.add(top.val);//把每次弹出的val值存入返回的数组中
                prev = top;//防止死循环,如果存入过当前节点,那么就再次弹出 存入
            }else {
                cur = top.right;//利用栈顶元素找到 兄弟节点
            }
        }
        return list;
    }
    /*
    二叉树中序遍历(非递归)
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;

        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {//遍历左子树
                stack.push(cur);
                cur = cur.left;
            }
            //右子树
            TreeNode top = stack.pop();//把栈顶元素弹出了
            list.add(top.val);//把每次弹出的val值存入返回的数组中
            cur = top.right;//利用栈顶元素找到 兄弟节点
        }
        return list;
    }
    /*
    二叉树前序遍历(非递归)
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;

        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {//遍历左子树
                stack.push(cur);
                list.add(cur.val);//把每次压入栈的val值存入返回的数组中
                cur = cur.left;
            }
            //右子树
            TreeNode top = stack.pop();//把栈顶元素弹出了
            cur = top.right;//利用栈顶元素找到 兄弟节点
        }
        return list;
    }
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}